package com.trgis.yhmap.util.wmtsproxy.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 限制访问次数的策略，如5分钟内单个用户调用上限30000
 * @author wangfy
 */
public class IPFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(IPFilter.class);

    @Autowired
    private AccessRuler ruler;

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;

        String ip = getIpAddr(request);
        if (checkIP(ip)){
            chain.doFilter(req, resp);
        } else {
            log.info("根据限流规则临时中断 {} 的访问", ip);
            return;
        }
    }

    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ipIsNull(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            if(ipIsNull(ip)){
                ip = request.getHeader("WL-Proxy-Client-IP");
                if(ipIsNull(ip)){
                    ip = request.getRemoteAddr();
                }
            }
        }
        return ip;
    }

    private boolean ipIsNull(String ip){
        return null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    private boolean checkIP(String ip){
        if (ipIsNull(ip)) {
            return true;
        }
        // 调用规则判断是否允许该ip继续访问
        return ruler.checkIP(ip);
    }
}
